package com.hzjq.core.impl

import com.hzjq.core.ErrorCode
import com.hzjq.core.callback.Callback
import com.hzjq.core.callback.OnScanCapCallback
import com.hzjq.core.loader.OnScanCapLoader
import com.hzjq.core.work.Works
import com.hzjq.core.worker.*
import io.reactivex.functions.Consumer

class ScanCapImpl : OnScanCapLoader {

    private var works: Works? = null

    override fun onScanCap(callback: OnScanCapCallback) {
        CheckerImpl().setCallback(Consumer {
            if (it) {
                cancel()
                works = Works.Builder.newBuilder()
                    .addWork(ClearChipStateWork(null, callback))
                    .addWork(ScanInnerModeWork(callback))
                    .addWork(ShipCapScanWork(callback))
                    .addWork(ReadCapWork(callback))
                    .build()
                    .queue()
            } else {
                callback.onError(ErrorCode.getErrorResult(103))
            }
        }).start()
    }

    override fun exitScan(callback: Callback<Boolean>) {
        CheckerImpl().setCallback(Consumer {
            if (it) {
                BackWork(callback).doWork()
                works?.onDestroy()
            } else {
                callback.onError(ErrorCode.getErrorResult(103))
            }
        }).start()
    }


    override fun cancel() {
        works?.onDestroy()
    }
}